#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
    TreeNode *dfs(TreeNode *ancester, TreeNode *p, TreeNode *q)
    {
        auto minval = min(p->val, q->val);
        auto maxval = max(p->val, q->val);
        auto pivot = ancester->val;
        if (maxval < pivot)
            return dfs(ancester->left, p, q);
        else if (pivot < minval)
            return dfs(ancester->right, p, q);
        if (minval <= pivot && pivot <= maxval)
            return ancester;
    }
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
    {
        return dfs(root, p, q);
    }
};